package com.lbd.system.controller;

import com.lbd.base.controller.BaseController;
import com.lbd.commons.Constants;
import com.lbd.commons.Result;
import com.lbd.commons.ResultState;
import com.lbd.finance.bean.vo.ExportRechargeVo;
import com.lbd.finance.bean.vo.ExportWithdrawVo;
import com.lbd.system.bean.*;
import com.lbd.system.bean.Dictionary;
import com.lbd.system.controller.vo.RecordVo;
import com.lbd.system.service.BindCardService;
import com.lbd.system.service.DictionaryService;
import com.lbd.system.service.RecordService;
import com.lbd.util.ExcelExportUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zzl on 2016/9/27.
 */
@RestController
@RequestMapping("/record")
public class RecordController extends BaseController {
    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    RecordService recordService;
    @Resource
    BindCardService bindCardService;
    @Autowired
    DictionaryService dictionaryService;

    /**
     * 根据查询条件分页查询流水记录
     *
     * @param page   第几页
     * @param rows   一条多少条
     * @param record 交易记录
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result list(@RequestParam(name = "page", required = false, defaultValue = "1") int page,
                       @RequestParam(name = "rows", required = false, defaultValue = "10") int rows,
                       RecordVo record) {
        Page<Record> util = recordService.findByPageConditionJpql(page, rows, record);
        //根据category参数判断是否需要获取关联表信息
        if (null != record.getType()) {
            if (record.getType() == Record.CATEGORY_2) {
                getRecordWithBankInfoList(util.getContent());
            }
        }


        return new Result(ResultState.SUCCESS, "查询成功", util);
    }

    /**
     * 交易记录导出
     *
     * @param request  request
     * @param response response
     * @param record   交易记录
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, RecordVo record) {
        //获取交易记录
        List<Record> list = recordService.findByConditionJpql(record);
        //按交易类别导出交易数据
        if (record.getType() == Record.CATEGORY_1) {
            exportRecharge(request, response, list);
        } else if (record.getType() == Record.CATEGORY_2) {
            getRecordWithBankInfoList(list);
            exportWithdraw(request, response, list);
        }


    }

    /**
     * 处理交易记录关联查询银行卡信息
     *
     * @param recordList 交易记录
     * @return
     */
    private List<Record> getRecordWithBankInfoList(List<Record> recordList) {

        for (Record rd : recordList) {
            List<BindCard> bindCardList = bindCardService.findByBankNo(rd.getBankCard());
            if (CollectionUtils.isNotEmpty(bindCardList)) {
                BindCard bindCard = bindCardList.get(0);
                Map<String, String> map = new HashMap<>();
//               map.put(Constants.T_BINDCARD_BANKNAME,bindCard.getBankCard().getBankName());
                map.put(Constants.T_BINDCARD_BANKNAME, bindCard.getBankCard().getBankName());
                map.put(Constants.T_BINDCARD_BANKBRANCH, bindCard.getBankBranch());
                rd.setRecordProperty(map);
            }
        }
        return recordList;
    }

    /**
     * 导出提现记录
     *
     * @param request  request
     * @param response response
     * @param records  交易记录
     */
    private void exportRecharge(HttpServletRequest request, HttpServletResponse response, List<Record> records) {
        List<ExportRechargeVo> exportList = new ArrayList<>();
        String keys = Constants.DIC_RECHARGE_TYPE.concat(",").concat(Constants.DIC_HANDINGFEE_TYPE).concat(",").concat(Constants.DIC_CHANNEL_TYPE);//获取字典项信息
        Map<String, Map<String, String>> dictionaryMap = dictionaryService.getDictionary(keys);
        for (Record rd : records) {
            Map<String, String> map = (Map) rd.getRecordProperty();
            ExportRechargeVo rechargeVo = getRechargeInfo(rd, map);
            rechargeVo.setUserName(rd.getUser().getTelephone());
            rechargeVo.setName(rd.getUser().getName());
            rechargeVo.setServiceChargeParty(dictionaryMap.get(Constants.DIC_HANDINGFEE_TYPE).get(rechargeVo.getServiceChargeParty()));
            rechargeVo.setState(dictionaryMap.get(Constants.DIC_RECHARGE_TYPE).get(rechargeVo.getState()));
            rechargeVo.setPlatform(dictionaryMap.get(Constants.DIC_CHANNEL_TYPE).get(rechargeVo.getPlatform()));
            exportList.add(rechargeVo);
        }
        ExcelExportUtils.exportExcel(request, response, DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"), ExportRechargeVo.class, exportList);
        log.info("充值文件生成...");
    }

    /**
     * 导出提现记录
     *
     * @param request  request
     * @param response response
     * @param records  交易记录
     */
    private void exportWithdraw(HttpServletRequest request, HttpServletResponse response, List<Record> records) {
        List<ExportWithdrawVo> exportList = new ArrayList<>();
        String keys = Constants.DIC_WITHDRAW_TYPE.concat(",").concat(Constants.DIC_HANDINGFEE_TYPE);//获取字典项信息
        Map<String, Map<String, String>> dictionaryMap = dictionaryService.getDictionary(keys);
        for (Record rd : records) {
            Map<String, String> map = (Map) rd.getRecordProperty();
            ExportWithdrawVo withdrawVo = getWithdrawInfo(rd, map);
            withdrawVo.setServiceChargeParty(dictionaryMap.get(Constants.DIC_HANDINGFEE_TYPE).get(withdrawVo.getServiceChargeParty()));
            withdrawVo.setState(dictionaryMap.get(Constants.DIC_WITHDRAW_TYPE).get(withdrawVo.getState()));
            exportList.add(withdrawVo);
        }
        ExcelExportUtils.exportExcel(request, response, DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"), ExportWithdrawVo.class, exportList);
        log.info("提现文件生成...");
    }

    /**
     * 获取提现记录
     *
     * @param rd  交易记录
     * @param map 提现信息
     * @return
     */
    private ExportWithdrawVo getWithdrawInfo(Record rd, Map<String, String> map) {
        ExportWithdrawVo withdrawVo = new ExportWithdrawVo();
        try {
            //copy from rd to withdrawVo
            BeanUtils.copyProperties(withdrawVo, rd);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.info(e);
        }
        if (withdrawVo.getCreatedDate() != null) {
            withdrawVo.setCreatedDate(DateFormatUtils.format(rd.getCreatedDate(), "yyyy-MM-dd HH:mm:ss"));//充值时间
        } else {
            withdrawVo.setCreatedDate("");
        }
//        withdrawVo.setActualAmount(withdrawVo.getAmount().subtract(withdrawVo.getFee()));//到账金额
        withdrawVo.setName(rd.getUser().getName());//用户姓名
        withdrawVo.setUserName(rd.getUser().getTelephone());//用户名
        if (null != map) {
            withdrawVo.setBankBranch(map.get(Constants.T_BINDCARD_BANKBRANCH));//银行支行
            withdrawVo.setBankName(map.get(Constants.T_BINDCARD_BANKNAME));//所属银行
        }

        withdrawVo.setAmount(BigDecimal.valueOf(Double.valueOf(rd.getAmount())).setScale(2));
        withdrawVo.setServiceCharge(BigDecimal.valueOf(Double.valueOf(rd.getServiceCharge())).setScale(2));
        withdrawVo.setActualAmount(BigDecimal.valueOf(Double.valueOf(rd.getActualAmount())).setScale(2));
        return withdrawVo;
    }

    /**
     * 获取充值记录
     *
     * @param rd  交易记录
     * @param map 充值信息
     * @return
     */
    private ExportRechargeVo getRechargeInfo(Record rd, Map<String, String> map) {
        ExportRechargeVo rechargeVo = new ExportRechargeVo();
        try {
            //copy from rd to rechargeVo
            BeanUtils.copyProperties(rechargeVo, rd);
            rechargeVo.setActualAmount(BigDecimal.valueOf(Double.valueOf(rd.getActualAmount())).setScale(2));
            rechargeVo.setAmount(BigDecimal.valueOf(Double.valueOf(rd.getAmount())).setScale(2));
            rechargeVo.setServiceCharge(BigDecimal.valueOf(Double.valueOf(rd.getServiceCharge())).setScale(2));
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.info(e);
        }
        if (rechargeVo.getCreatedDate() != null) {
            rechargeVo.setCreatedDate(DateFormatUtils.format(rd.getCreatedDate(), "yyyy-MM-dd HH:mm:ss"));//充值时间
        } else {
            rechargeVo.setCreatedDate("");
        }

        if (rd.getFinishTime() != null) {
            rechargeVo.setFinishTime(DateFormatUtils.format(rd.getFinishTime(), "yyyy-MM-dd HH:mm:ss"));//到账时间
        } else {
            rechargeVo.setFinishTime("");

        }

        return rechargeVo;
    }
}
